import React, {Component, createRef} from 'react'
import CommonBread from "../components/CommonBread";
import {Button, Form, Input, message, Modal, Radio, Space, Upload} from "antd";
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import ChannelSelect from "./components/ChannelSelect";
import {baseURL} from "../../utils/request";
import {addArticle, editArticle, getArticle} from "../../api/article";
import qs from 'qs'

const {Group} = Radio

export default class ArticlePublish extends Component {
  formRef = createRef()
  state = {
    fileList: [],
    imageType: 1,
    isVisible: false,
    imgUrl: '',
    id: qs.parse(this.props.location.search, {ignoreQueryPrefix: true})?.id
  }

  uploadImages = ({fileList}) => {
    this.setState({
      fileList,
    })
  }

  componentDidMount() {
    this.getArticleDetail()
  }

  getArticleDetail = async () => {
    //  判断是否有id
    if (this.state.id) {
      const res = await getArticle(this.state.id)

      this.formRef.current.setFieldsValue({
        ...res.data,
        type: res.data.cover.type
      })
      this.setState({
        fileList: res.data.cover.images.map(url => ({url})),
        imageType: res.data.cover.type
      })
    }
  }

  changeRadio = e => {
    this.setState({
      imageType: e.target.value
    })
  }

  onImgPreview = file => {
    this.setState({
      isVisible: true,
      imgUrl: file?.response?.data?.url || file.url
    })
  }

  save = async ({images, type, ...values}, draft = false) => {
    // 判断发布还是编辑
    //values表单的值
    if (type !== this.state.fileList.length) {
      message.error('传的图片数量不一致')
      return
    }
    // 本地上传
    const imageList = this.state.fileList.map(item => item?.response?.data?.url || item.url)
    const params = {
      draft,
      ...values,
      cover: {
        type,
        images: imageList
      }
    }
    //  判断是否存在id
    // 如果有id 则为编辑状态
    if (this.state.id) {
      //  编辑
      await editArticle({
        ...params,
        id: this.state.id
      })
    } else {
      //  新增
      // 否则为新增状态
      await addArticle(params)
    }

    message.success(this.state.id ? '编辑成功' : '发布成功')
    this.props.history.push('/home/article')
  }

  handleFinish = values => {
    this.save(values, false)
  }

  addDraft = async () => {
    // 存入草稿逻辑
    const values = await this.formRef.current.validateFields()
    this.save(values, true)
  }

  render() {
    return <div className="home">
      <CommonBread title={this.state.id ? '编辑文章' : '发布文章'}/>
      <Form
        labelCol={{span: 4}}
        wrapperCol={{span: 8}}
        initialValues={{
          content: '',
          type: 1,
        }}
        ref={this.formRef}
        onFinish={this.handleFinish}
      >
        <Form.Item
          label={'标题'}
          name={'title'}
          rules={[{required: true, message: '标题不能为空'}]}
        >
          <Input placeholder={'请输入文章标题'}/>
        </Form.Item>
        <Form.Item
          label={'频道'}
          name={'channel_id'}
          rules={[{required: true, message: '频道不能为空'}]}
        >
          <ChannelSelect/>
        </Form.Item>
        <Form.Item label={'封面'} name={'type'}>
          <Group
            onChange={this.changeRadio}
          >
            <Radio value={1}>单图</Radio>
            <Radio value={3}>三图</Radio>
            <Radio value={0}>无图</Radio>
          </Group>
        </Form.Item>
        <Form.Item
          name={'images'}
          wrapperCol={{offset: 4}}
        >
          <Upload
            onPreview={this.onImgPreview}
            listType="picture-card"
            name={'image'}
            action={`${baseURL}/upload`}
            onChange={this.uploadImages}
            fileList={this.state.fileList}
            maxCount={this.state.imageType}
          >
            上传
          </Upload>
        </Form.Item>
        <Form.Item label={'内容'} name={'content'}>
          <ReactQuill theme={'snow'} style={{width: 400, height: 200}}/>
        </Form.Item>
        <Form.Item wrapperCol={{offset: 4}}>
          <Space>
            <Button htmlType={'submit'} style={{marginTop: 40}}>发布文章</Button>
            <Button onClick={this.addDraft} style={{marginTop: 40}}>存入草稿</Button>
          </Space>
        </Form.Item>
      </Form>

      <Modal
        visible={this.state.isVisible}
        onCancel={() => this.setState({isVisible: false})}
        style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}
        footer={null}
      >
        <img width={500} src={this.state.imgUrl} alt=""/>
      </Modal>
    </div>
  }
}
